package cn.mall.cart.service.impl;

import cn.mall.cart.config.CartInterceptor;
import cn.mall.cart.feign.ProductFeignService;
import cn.mall.cart.service.CartService;
import cn.mall.cart.to.UserInfoTo;
import cn.mall.cart.vo.Cart;
import cn.mall.cart.vo.CartItem;
import cn.mall.cart.vo.SkuInfoVo;
import cn.mall.common.constant.CartConstant;
import cn.mall.common.utils.R;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static cn.mall.common.constant.CartConstant.CART_PREFIX;

@Service("cartService")
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 线程池异步调用mall—product进行购物车操作
     * @param skuId
     * @param num
     * @return
     */


    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object,Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        System.out.println("res = " + res);
        /**
         * 判断是否登录
         */
        if (StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();

            //远程查询mall-product 查询当前要添加到购物车商品的信息数据(添加新商品到购物车)， 开启第一个线程
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() ->{
                System.out.println("skuId = " + skuId);
                R skuInfo = productFeignService.info(skuId);
                System.out.println("skuInfo = " + skuInfo);
                SkuInfoVo data = skuInfo.getData("data", new TypeReference<SkuInfoVo>() {});
                System.out.println("data = " + data);
                cartItem.setCheck(true);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setCount(num);
                cartItem.setPrice(data.getPrice());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
            },executor);
            //远程调用mall-product模块，拿到顾客所选套餐信息 ，开启第二个线程
            CompletableFuture<Void> getSkuSaleAttrValue = CompletableFuture.runAsync(() ->{
                List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
                cartItem.setSkuAttr(skuSaleAttrValue);

            }, executor);
            CompletableFuture.allOf(getSkuInfo,getSkuSaleAttrValue).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;

        }
        //没有登录
        else {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            System.out.println("没有登录cartItem.getCount() = " + cartItem.getCount());
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 查询某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        System.out.println("str = " + str);
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        System.out.println("重定向1cartItems数据详情 = " + cartItem);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //判断是否登录
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId()!=null){
            String cartKey = CART_PREFIX +userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            //临时购物车添加到在线购物车
            List<CartItem> tempCartItem = getCartItems(tempCartKey);
            if (tempCartItem !=null){

                for (CartItem item : tempCartItem) {
                    addCart(item.getSkuId(), item.getCount());

                }
                //qing空临时购物车
                clearCart(tempCartKey);

            }
            //登录后购物车
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

            //登录 String cartKey =CART_PREFIX +
        }else {
            //未登录
            String cartKey =CART_PREFIX + userInfoTo.getUserKey();
            System.out.println("最后cartKey"+cartKey);
            //huoqu临时购物车的购物项
            List<CartItem> cartItem = getCartItems(cartKey);
            if (cartItem != null) {
                for (CartItem item:cartItem){
                    System.out.println("拿到价格"+item.getPrice());
                    System.out.println("拿到总价格"+item.getTotalPrice());


                }
            }
            else {
                System.out.println("出错了！！！！！！！！！ " + cartItem);
            }
            System.out.println("未登录或渠道数据"+cartItem);

            cart.setItems(cartItem);


        }

        return cart;
    }

    @Override
    public List<CartItem> getUserCartItems(String cartKey) {


      /*  //UserInfoTo为空
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();*/

        System.out.println("哈哈哈哈哈哈哈哈哈哈哈userInfoTo = " + cartKey);
        /*String cartKey = CART_PREFIX+userInfoTo.getUserId();*/
        /*String cartKey = CART_PREFIX+userInfoTo.getUserKey();
        System.out.println("cartKey = " + cartKey);*/
//        cartOps.get(cartKey);

       List<CartItem> cartItem = getCartItems(cartKey);
        System.out.println("cartItem = 55555555555555555555555" + cartItem);
        //获取所有被选中的购物项
        assert cartItem != null;
        List<CartItem> collect = cartItem.stream()
                .filter(item -> item.getCheck())
                .map(item -> {
                    //TODO 1.更新为最新的价格
                    BigDecimal price=productFeignService.getPrice(item.getSkuId());
                    item.setPrice(price);
                    System.out.println("price =333333333333333333 " + price);
                    return item;
                })
                .collect(Collectors.toList());

        return collect;
    }


    /**
     * 获取要操作购物车
     * @return
     */

    private BoundHashOperations<String, Object,Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        System.out.println("userInfoTo = " + userInfoTo);
        String cartKey="";
        if (userInfoTo.getUserId()!= null){
            cartKey = CART_PREFIX+userInfoTo.getUserId();
            System.out.println("CartKey1 = " + cartKey);
        }else {
            cartKey =CART_PREFIX+userInfoTo.getUserKey();
            System.out.println("CartKey2 = " + cartKey);

        }
        BoundHashOperations<String, Object,Object> operations = redisTemplate.boundHashOps(cartKey);



        return operations;
    }
    private List<CartItem> getCartItems(String cartKey){
        System.out.println("我的cartKey = " + cartKey);
        BoundHashOperations<String, Object,Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!= null && values.size()>0){
            List<CartItem> collect =values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem item = JSON.parseObject(str, CartItem.class);
                return item;
            }).collect(Collectors.toList());
            System.out.println("获取dao购物车里面的所有商品");

            return collect;
        }
        System.out.println("没有获取购物车里面的所有商品");
        return null;
    }
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);

    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public void allChecked() {

    }


}
